const sequelize = require('../db.js')
const { QueryTypes } = require('sequelize');
const router = require('koa-router')()
const jwt = require('koa-jwt');
router.prefix('/cart')
router.get('/',jwt({ secret:'yan' }),async(ctx)=>{
	let {id} = ctx.state.user
	ctx.body={
		code:200,
		data:await sequelize.query(`select * from (select * from (select goodsId,goodsNum,selected,skuId from cart where userId=${id}) as usercart left join goods2 on id=usercart.goodsId) as b,goodssku as a where b.skuId=a.id`, { type: QueryTypes.SELECT })
	}
})
router.post('/add',jwt({ secret:'yan' }),async(ctx)=>{
	let {id} = ctx.state.user
	console.log(ctx.state)
	let {goodsId,goodsNum,selected,skuId} = ctx.request.body
	const r = await sequelize.query(`insert into cart (id,goodsId,userId,goodsNum,selected,skuId) values (null,${goodsId},${id},${goodsNum},${selected},${skuId})`)
	ctx.body={
		code:200,
		data:'添加成功'
	}
})
router.post('/update',async(ctx)=>{
	let {id} = ctx.request.body
	const r = await sequelize.query(`update cart set selected=selected ^ 1 where id=${id}`)
	ctx.body={
		code:200,
		data:'修改成功'
	}
})
module.exports = router